import { Service } from 'egg';
import { v4 } from 'uuid';
import { LoginIn, RegisterGender, RegisterIn } from '../dto/in/memberIn';
import { LoginOut } from '../dto/out/memberOut';
import CommonUtil from '../src/decorator/commonUtil';
import IDBModel from '../src/interface/DBModel';

export default class Member extends Service {

    /**用户注册 */
    public async register(_params: RegisterIn) {
        if (await this.service.mysql.any(IDBModel.tables.tb_member, {
            where: CommonUtil.pick(_params, ["account"])
        })) {
            throw new Error("账号重复");
        }
        else {
            await this.app.mysql.beginTransactionScope(async (conn) => {
                const _memberId = v4();
                await this.service.mysql.insert<IDBModel.Member>(IDBModel.tables.tb_member, {
                    account: _params.account,
                    password: _params.password,
                    nickname: _params.nickname,
                    registerWith: 0,
                    gender: RegisterGender.male,
                    id: _memberId
                }, conn);
                await this.service.contacts.makeFirends(_memberId, "0441e758-252f-4574-8ff3-1929b0e736b8", conn);
                return { success: true };
            }, this.ctx);
        }
    }

    /**用户登录 */
    public async login(_params: LoginIn): Promise<LoginOut> {
        let select = await this.service.mysql.firstOrDefault<IDBModel.Member>(IDBModel.tables.tb_member, {
            where: CommonUtil.pick(_params, ["account", "password"])
        });
        if (!select) {
            throw new Error("账号或密码错误");
        }
        else {
            return { token: this.app.jwt.sign({ id: select.id }, this.config.jwt.secret), memberId: select.id };
        }
    }

    /**通过Token获取用户ID */
    public getMemberIdByToken() {
        return (this.app.jwt.decode(this.ctx.request.headers["token"] as string) as unknown as { id: string }).id;
    }

    /**获取用户信息 */
    public async memberInfoById(memberId?: string) {
        memberId = memberId ?? this.getMemberIdByToken();
        let select = await this.service.mysql.firstOrDefault<IDBModel.Member>(IDBModel.tables.tb_member, {
            where: { id: memberId },
            columns: ["account", "avatar", "cover", "gender", "id", "nickname", "title", "signature"]
        });
        if (!select) {
            throw new Error("查找失败");
        }
        else {
            return select;
        }
    }

    /**修改昵称 */
    public async editNickname(nickname: string) {
        this.service.mysql.updateById(IDBModel.tables.tb_member, this.getMemberIdByToken(), { nickname });
    }




}

